package com.linkdood.app.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.datetime.standard.InstantFormatter;

import java.text.ParseException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Locale;

/**
 * 转换 LocalDateTime 为 ISO-8601 "2020-10-10T10:10:10.000Z" 格式
 *
 * @author hycao
 */
@Slf4j
public class LocalDateTimeConvert implements Converter<String, LocalDateTime> {


    @Override
    public LocalDateTime convert(String source) {
        try {
            InstantFormatter instantFormatter = new InstantFormatter();
            Instant instant = instantFormatter.parse(source, Locale.US);
            return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        } catch (ParseException e) {
            log.warn("LocalDateTime parse failed, cause by:", e);
        }
        return null;
    }
}
